import * as services from 'services/message';

export default {

  namespace: 'message',
  //医生和患者发送消息

  state: {
    doctors: [],
    messages: [],
    comments: [],
    unread: 0,
    showTools: false,
    totalCount: "",
    controlClientHeight: 0,
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },

    reload(state, action) {
      return { ...state, comments: [...state.comments, action.payload] };
    },
  },

  effects: {
    *toggleTools({ payload: { showTools } }, { put }) {
      yield put({ type: 'save', payload: { showTools: !showTools } })
    },

    *fetchMessages({ payload }, { call, put }) {
      // 获取最近消息列表
      let auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
      if(auth){
          let patientId = auth.patientId;
          let messages = yield call(services.queryMessageList,  patientId);
          messages = messages.data;
          if (!messages) {
            messages = [];
          }

          const unread = messages.reduce((count, cur) => count + cur.badge, 0);
          yield put({
            type: 'save',
            payload: {
              unread,
              messages,
            },
          });
      }
    },
    *fetchDoctors({ payload }, { call, put }) {
      // 获取发送信息的医生列表
      let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      const doctors = yield call(services.queryDoctorList, patientId);
      yield put({ type: 'save', payload: { doctors: doctors.data || [] } });
    },

    *fetchMessage({ payload: {doctorId, page, size} }, { call, put }) {
      // 获取与医生聊天记录
      let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      const comments = yield call(services.queryMessageDetail, patientId, doctorId, page, size);
      yield put({ type: 'save', payload: { comments: comments.data.reverse() || [] , totalCount: comments.totalCount} });
    },

    *sendMessage({ payload: { doctorId, text, image, ...rest } }, { call, put }) {
      const mock = (fields) => ({
        Sendtype: 0,
        Updatetime: Date.now(),
        ...fields,
      });

      if (text) {
        // 发送文字消息
        let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
        const { data } = yield call(services.sendTextMessage, { doctorId, text , patientId});
        yield put({
          type: 'reload',
          payload: mock({
            Id: data,
            Msgtype: 0,
            Messages: text,
          }),
        });
      }
      if (image) {
        // 发送图片消息
        let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
        const { data } = yield call(services.sendImageMessage, { doctorId, mediaId: image, patientId });

        yield put({
          type: 'reload',
          payload: mock({
            Id: data || Date.now(),
            Msgtype: 1,
            Messages: rest.localId,
          }),
        });
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query, ...rest }) => {
        if (/doctor$/.test(pathname)) {
          dispatch({ 
              type: 'fetchMessages', 
          });
        }

        if (/doctor\/\d+$/.test(pathname)) {
          dispatch({type: 'inquiry/fetch'});
          dispatch({
            type: 'fetchMessage',
            payload: {
              doctorId:rest.state.doctorId,
              page: 0,
              size: 10
            }
          });
           let auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
           if(auth){
            var hub = $.connection.myHub;
            var names = auth.name;
            var ids = auth.patientId;
            $.connection.hub.qs = {patientName: names,id: ids};
            $.connection.hub.url = "http://chat.tcm-ai.com/signalr";
            $.connection.hub.start({jsonp:true}).done(() => {
                console.log("启动成功！");
            });
            $.connection.hub.error((error) => {
                console.log(error)
                console.log("启动失败！")
            });
           }
        }
      });
    },
  },
}
